<?php
namespace Admin\Common;

use Twig\Error\Error;
use PhalApi\Exception\BadRequestException;

/**
 * 管理后台的控制器基类
 * @dogstar 20201103
 */
class Controller extends Api {

    // 请求
    protected $request;

    // 视图数据
    protected $viewData = array(
        'view_title' => '首页',
    );

    public function __construct() {
        $this->request = \PhalApi\DI()->request;
    }

    // 会话检测
    protected function userCheck() {
        if (!$this->isNeedLogin) {
            return;
        }

        $this->doUserCheck();
    }
    
    protected function doUserCheck() {
        $isLogin = \PhalApi\DI()->admin->check(false);
        if (!$isLogin) {
            header('Location: /admin/?s=Site.Login');
            eixt();
        }

        // 权限
        try {
            \PhalApi\DI()->iadminosRights->check();
        } catch (BadRequestException $ex) {
            return $this->renderError('权限不足', $ex->getMessage());
        }
    }

    public function assign($name, $value) {
        $this->viewData[$name] = $value;
    }

    /**
     * 渲染错误
     */
    protected function renderError($errorTitle, $errorMessage = null) {
        $data = array(
            'error_title' => $errorTitle,
            'error_message' => $errorMessage,
        );
        return $this->render('error.html', $data, false);
    }

    /**
     * 页面渲染
     */
    public function render($tpl, array $data = array(), $isCommon = true) {
        header('Content-type: text/html; charset=utf-8');

        $di = \PhalApi\DI();

        // 公共目录
        $data['ADMIN_PUBLIC_PATH'] = IADMINOS_PUBLIC_PATH;
        $data['PROJECT_NAME'] = $di->config->get('admin.name');
        $data['IADMINOS_VERSIOIN'] = IADMINOS_VERSIOIN;

        $data['ADMIN_MENUS'] = $di->config->get('admin.menus');

        // HACK 菜单高亮
        $curURI = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';
        foreach ($data['ADMIN_MENUS'] as &$menuTopRef) { 
            $pTop = strpos($menuTopRef['href'], '?') ? substr($menuTopRef['href'], 0, strpos($menuTopRef['href'], '?')) : $menuTopRef['href'];
            if (!empty($menuTopRef['items'])) {
                $isHigh = false;
                foreach ($menuTopRef['items'] as &$menuSubRef) {
                    $p = strpos($menuSubRef['href'], '?') ? substr($menuSubRef['href'], 0, strpos($menuSubRef['href'], '?')) : $menuSubRef['href'];
                    if ($p == $curURI) {
                        $menuSubRef['active'] = 'active';
                        $isHigh = true;
                    }
                }
                if ($isHigh) {
                    $menuTopRef['active'] = 'menu-open';
                }
            } else if ($pTop == $curURI) {
                $menuTopRef['active'] = 'active';
            }
        }
        
        // 管理员
        $data['ADMIN_USERNAME'] = $di->admin->username;
        $data['ADMIN_ID'] = $di->admin->id;
        $data['ADMIN_ROLE'] = $di->admin->role;

        // 合并参数
        $data = array_merge($this->viewData, $data);
        
        try {
			// 正文内容
			$data['view_content'] = $di->twig->render($tpl, $data);
	
        } catch (Error $ex) {
        	$data['view_content'] = $ex->getMessage() . ($di->debug ? '<hr/><br/>' . str_replace("\n", '<br/>', $ex->getTraceAsString()) : '');
        }
        
		echo $isCommon ? $di->twig->render('common.html', $data) : $data['view_content'];
	
		exit();
    }
}

